<template>
  <div class="ExhibitionInfoForm-container">
    <el-form :model="form" class="form">
      <div class="title">广告上传</div>

      <div class="form-item">
        <div class="label">广告图片</div>
        <el-avatar
          :src="getImageUrl()"
          shape="square"
          style="
            width: 500px;
            height: 100px;
            object-fit: cover;
            background-color: #fff;
            border: 2px solid #6ccceb;
          "
        />
        <input
          ref="fileInput"
          type="file"
          accept="image/jpeg,image/jpg,image/png"
          style="display: none"
          @change="handleFileChange"
        />
      </div>

      <el-form-item style="margin: 20px 0">
        <el-button
          v-if="props.mode !== 'view'"
          size="large"
          type="success"
          @click="triggerFileUpload"
        >
          上传
        </el-button>
        <el-button
          v-if="props.mode === 'add' || props.mode === 'edit'"
          size="large"
          @click="onSubmit"
        >
          {{ props.mode === "add" ? "提交" : "修改" }}
        </el-button>
      </el-form-item>
      <div class="bottom">
        <div class="bottom-top">广告图片上传格式:JPG，PNG，IPEG</div>
        <div class="bottom-down">
          资料反复提交会覆盖之前资料，请您确保资料完整准确。资料上传截止日期:2022年3月10日。
        </div>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import {
  applyAdvertisement,
  uploadImage,
  updateAdvertisement
} from "@/api/advertisement";
import {
  validateUploadFile,
  FileType,
  updateUploadConfig
} from "@/utils/uploadFile";
import type { ImagePath } from "@/api/advertisement";
import { getExhibitorId } from "@/utils/getExhibitorId";

interface Props {
  mode?: "add" | "view" | "edit";
  initialData?: any;
}

const props = withDefaults(defineProps<Props>(), {
  mode: "add",
  initialData: null
});

const emit = defineEmits(["cancel", "confirm"]);

// do not use same name with ref
const form = ref({
  exhibitor_id: getExhibitorId() || 0,
  title: "产品推广广告",
  description: "最新产品推广，欢迎咨询",
  status: 3,
  ad_img: ""
});

// 图片预览URL
const imagePreview = ref("");

// 获取图片URL
const getImageUrl = () => {
  // 如果是编辑或新增模式且有预览图片，使用预览图片
  if (props.mode !== "view" && imagePreview.value) {
    if (imagePreview.value.startsWith("data:")) {
      return imagePreview.value;
    }
    if (imagePreview.value.startsWith("/")) {
      const BASE_URL = "https://exhibition-bucket.oss-cn-beijing.aliyuncs.com";
      return `${BASE_URL}${imagePreview.value}`;
    }
    if (imagePreview.value.startsWith("http")) {
      return imagePreview.value;
    }
    return imagePreview.value;
  }

  // 如果有表单数据中的图片
  if (form.value.ad_img) {
    // 如果是Base64数据，直接使用
    if (form.value.ad_img.startsWith("data:")) {
      return form.value.ad_img;
    }
    // 如果是相对路径，使用新的OSS域名拼接
    if (form.value.ad_img.startsWith("/")) {
      const BASE_URL = "https://exhibition-bucket.oss-cn-beijing.aliyuncs.com";
      return `${BASE_URL}${form.value.ad_img}`;
    }
    // 如果是完整URL，直接使用
    if (form.value.ad_img.startsWith("http")) {
      return form.value.ad_img;
    }
    return form.value.ad_img;
  }

  return "/placeholder-ad.png";
};

// 监听初始数据变化
watch(
  () => props.initialData,
  newData => {
    if (newData) {
      // 更新表单数据
      form.value = { ...newData };
      // 查看模式下不设置预览，让getImageUrl使用表单数据
      if (props.mode === "view") {
        imagePreview.value = "";
      } else if (newData.ad_img) {
        // 编辑模式下设置预览，但不清空，让getImageUrl处理路径
        imagePreview.value = newData.ad_img;
      } else {
        imagePreview.value = ""; // 清空预览
      }
    } else {
      // 清空表单数据
      form.value = {
        exhibitor_id: getExhibitorId() || 0,
        title: "产品推广广告",
        description: "最新产品推广，欢迎咨询",
        status: 3,
        ad_img: ""
      };
      // 清空图片预览
      imagePreview.value = "";
    }
  },
  { immediate: true }
);

// 组件挂载时初始化
onMounted(() => {
  // 设置图片上传配置
  updateUploadConfig(FileType.IMAGE, {
    maxSize: 10 * 1024 * 1024, // 10MB
    maxSizeMB: 10 // 10MB
  });
});

const onSubmit = async () => {
  try {
    // 表单验证
    console.log("提交时form.value:", form.value);
    console.log("ad_img值:", form.value.ad_img);
    console.log("ad_img长度:", form.value.ad_img?.length);

    if (!form.value.ad_img) {
      ElMessage.error("请上传广告图片");
      return;
    }

    // 直接使用图片路径
    const normalizedAdImg = form.value.ad_img;

    const submitData = {
      ...form.value,
      ad_img: normalizedAdImg
    };

    // 调试信息：检查提交数据中是否包含exhibitor_id
    console.log("广告申请 - 表单数据:", form.value);
    console.log("广告申请 - 提交数据:", submitData);
    console.log("广告申请 - exhibitor_id:", submitData.exhibitor_id);

    let result: any;

    if (props.mode === "add") {
      // 新增模式：调用申请广告API
      result = await applyAdvertisement(submitData);
      if (result.code === 1) {
        ElMessage.success("广告申请成功！");
      } else {
        ElMessage.error(result.msg || "广告申请失败！");
        return;
      }
    } else if (props.mode === "edit") {
      // 修改模式：调用更新广告API
      result = await updateAdvertisement(submitData);
      if (result.code === 1) {
        ElMessage.success("广告修改成功！");
      } else {
        ElMessage.error(result.msg || "广告修改失败！");
        return;
      }
    }

    emit("confirm", submitData);
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败，请重试");
  }
};

// 上传Logo
const fileInput = ref<HTMLInputElement | null>(null);

const triggerFileUpload = () => {
  fileInput.value?.click();
};

// 上传图片到服务器
const uploadImageToServer = async (file: File): Promise<string | ImagePath> => {
  try {
    const response: any = await uploadImage(file);

    if (response.code === 1) {
      // 兼容后端返回 string 或 { url, full_url }
      return response.data as string | ImagePath;
    } else {
      throw new Error(response.msg || "图片上传失败");
    }
  } catch (error) {
    console.error("图片上传失败:", error);
    throw error;
  }
};

const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files ? target.files[0] : null;
  if (file) {
    // 使用uploadFile工具进行文件验证
    const validationResult = validateUploadFile(file);
    if (!validationResult.isValid) {
      ElMessage.error(validationResult.error || "文件验证失败");
      return;
    }

    try {
      // 生成预览URL
      imagePreview.value = URL.createObjectURL(file);

      // 上传图片到服务器（可能返回字符串或对象）
      const imagePath = await uploadImageToServer(file);
      console.log("服务器返回的图片路径:", imagePath);

      if (!imagePath) {
        throw new Error("上传失败，没有获取到图片路径");
      }

      // 解析为字符串 url
      const urlString =
        typeof imagePath === "string"
          ? imagePath
          : imagePath.url || imagePath.full_url || "";

      if (!urlString) {
        throw new Error("上传失败，未解析到有效的图片地址");
      }

      // 将服务器返回的图片路径保存到表单
      form.value.ad_img = urlString;
      // 清空预览，让getImageUrl使用表单数据
      imagePreview.value = "";
      console.log("赋值后的form.value.ad_img:", form.value.ad_img);
      console.log("赋值后的form.value:", form.value);

      ElMessage.success("广告图片上传成功");
    } catch (error) {
      console.error("广告图片上传失败:", error);
      ElMessage.error("广告图片上传失败，请重试");
      // 清空预览
      imagePreview.value = "";
      // 清空表单数据
      form.value.ad_img = "";
    }
  }
};
</script>
<style lang="scss" scoped>
.ExhibitionInfoForm-container {
  .form {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;

    .title {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 300px;
      height: 50px;
      margin: 20px 0;
      font-size: 18px;
      font-weight: bold;
      background-color: #f8f9fa;
    }

    .form-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 100%;
      margin-bottom: 20px;

      .label {
        width: 500px;
        margin-bottom: 8px;
        font-weight: 500;
        color: #333;
        text-align: left;
      }
    }

    .bottom {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;
      color: red;
    }
  }
}
</style>
